package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Permission;
import cn.wolfcode.queryobject.QueryObject;
import cn.wolfcode.resultpage.JsonResult;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload(){
        permissionService.reload();
        return new JsonResult(true,"123");
    }

    // 处理查询所有部门请求
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        // 调用分页查询的方法
        PageInfo<Permission> PageInfo = permissionService.query(qo);
        // 往模型存数据
        model.addAttribute("PageInfo",PageInfo);
        // 找视图
        return "permission/list";
    }

    @RequiredPermission(name="权限删除",expression="permission:delete")
    // 处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){

            try {
                if (id != null)
                permissionService.delete(id);
                return new JsonResult();
            } catch (Exception e) {
                e.printStackTrace();
                // 告诉用户操作失败
                return new JsonResult(false,"操作失败");
            }
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id,Model model){
      if(id != null){ // 表示去修改
          Permission permission = permissionService.selectOne(id);
          model.addAttribute("permission",permission);
      }
      return "permission/input";
    }
    @RequiredPermission(name="权限修改",expression="permission:saveOrUpdate")
    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission dept) {
        System.out.println(dept);
        if (dept.getId() != null){ // 修改
            permissionService.update(dept);
        }
        else{  // 新增
            permissionService.insert(dept);
        }

        return "redirect:/permission/list.do";// 让浏览器重新发送一次请求
    }
}
